package controller

import (
	"github.com/gin-gonic/gin"
	model2 "publish/app/account/model"
	"publish/model"
	"publish/pub-lib/baijia"
	"net/url"
	"github.com/astaxie/beego/httplib"
	"errors"
	"encoding/json"
	"publish/pub-lib"
	"github.com/astaxie/beego"
	"strconv"
)

var (
	PraseRemoteAddr = beego.AppConfig.String("prase_api")
)

func PraseArticle(articleUrl string) (*baijia.FeedArticle,error){
	api := PraseRemoteAddr + `/article/feed?url=`+url.QueryEscape(articleUrl)
	feedArticle := baijia.FeedArticle{}
	if err := httplib.Get(api).ToJSON(&feedArticle); err != nil {
		return nil,err
	}

	if len(feedArticle.Title) == 0 || len(feedArticle.Feed) == 0{
		return nil,errors.New("解析内容为空："+api)
	}

	return &feedArticle,nil
}

func AddTask(ctx *gin.Context) Result{
	task := model.PubTaskHttp{}
	if err := ctx.BindJSON(&task); err != nil {
		return ErrorResult(err)
	}

	article,err := PraseArticle(task.ArticleUrl)
	if err != nil{
		beego.Error(err)
		return ErrorResult(err)
	}

	if len(task.Title) > 0{
		article.Title = task.Title
	}

	articleBytes,err := json.Marshal(article)
	if err != nil{
		beego.Error(err)
		return ErrorResult(err)
	}

	pub := model.PubTask{
		AccountId: task.AccountId,
		ArticleCat: task.ArticleCat,
		Article:    string(articleBytes),
		Tag:        "",
		Type:       task.Type,
		Status:     model.Pub_Status_Nopub,
	}

	pubTask, err := model.InsertPubTask(pub)
	if err != nil {
		beego.Error(err)
		return ErrorResult(err)
	}

	return DataResult(pubTask)
}

func GetTask(ctx *gin.Context) Result{
	pub, err := model.GetNeedPubTask()
	if err != nil {
		beego.Error(err)
		return ErrorResult(err)
	}

	feedArticle := baijia.FeedArticle{}
	err = json.Unmarshal([]byte(pub.Article),&feedArticle)
	if err != nil{
		beego.Error(err)
		return ErrorResult(err)
	}

	account,err := model2.GetAccountById(pub.AccountId)
	if err != nil{
		beego.Error(err)
		return ErrorResult(err)
	}

	task := pub_lib.Task{
		Id:pub.Id,
		Article: feedArticle,
		Type:pub.Type,
		Category:pub.ArticleCat,

		Plat:account.Plat,
		Cookies:account.Cookie,
		PlatParams: map[string]string{},
	}

	return DataResult(task)
}


func Callback(ctx *gin.Context) Result{
	result := model.PubResult{}
	if err := ctx.BindJSON(&result); err != nil {
		beego.Error(err)
		return ErrorResult(err)
	}

	task, err := model.PubTaskById(result.TaskId)
	if err != nil {
		beego.Error(err)
		return ErrorResult(err)
	}

	task.Status = result.Type
	task.Msg = result.Result

	if _, err = model.UpdatePubtask(task); err != nil {
		beego.Error(err)
		return ErrorResult(err)
	}

	return DataResult(task)
}

func RePublish(ctx *gin.Context) Result{
	idQ := ctx.DefaultQuery("id","0")
	id,_ := strconv.Atoi(idQ)

	if err := model.RePublish(id); err != nil {
		beego.Error(err)
		return ErrorResult(err)
	}

	return SuccessResult
}

func ListPubTask(ctx *gin.Context) Result{
	pubTasks,err := model.ListPubTask()
	if err != nil {
		return ErrorResult(err)
	}

	return DataResult(pubTasks)
}

func ListPubTaskByPage(ctx *gin.Context) Result{

	pageQ := ctx.DefaultQuery("page","1")
	sizeQ := ctx.DefaultQuery("size","10")
	page,_ := strconv.Atoi(pageQ)
	size,_ := strconv.Atoi(sizeQ)

	result,count,err := model.ListPubTaskByPage(page,size)
	if err != nil{
		return ErrorResult(err)
	}

	tasks := []model2.Task{}
	for _,pub := range result{
		account,err := model2.GetAccountById(pub.AccountId)
		if err != nil{
			beego.Error(err)
			return ErrorResult(err)
		}

		feedArticle := baijia.FeedArticle{}
		err = json.Unmarshal([]byte(pub.Article),&feedArticle)
		if err != nil{
			beego.Error(err)
			return ErrorResult(err)
		}

		task := model2.Task{
			Id:pub.Id,
			Title: feedArticle.Title,
			Account: *account,
			Status: pub.Status,
			Result: pub.Msg,
			CreateTime: pub.CreateTime,
		}

		tasks = append(tasks,task)
	}

	return DataResult(model2.Page{Page:page,PageSize:size,Count:count,Data:tasks})
}




